package cn.john.hrm.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

// 声明为配置类
@Configuration
// 作为资源服务方
@EnableResourceServer
// 开启注解支持
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class HrmGlobalResourceConfig extends ResourceServerConfigurerAdapter {
    @Value("${oauth.resourceId}")
    private String resourceId;

    /**
     * 配置资源方的相关信息
     * @param resources
     * @throws Exception
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        // 配置资源服务的id
        resources.resourceId(resourceId);
        // 配置校验token的服务
        //resources.tokenServices(tokenService());
        // jwt本地校验
        resources.tokenStore(tokenStore());
    }

    private TokenStore tokenStore() {
        return new JwtTokenStore(getTokenConverter());
    }

    private static String key = "JohnWick";

    @Bean
    public JwtAccessTokenConverter getTokenConverter() {
        JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter();
        // 设置签名
        tokenConverter.setSigningKey(key);
        return tokenConverter;
    }

    /*private ResourceServerTokenServices tokenService() {
        RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
        remoteTokenServices.setClientId("admin");
        remoteTokenServices.setClientSecret("1");
        remoteTokenServices.setCheckTokenEndpointUrl("http://localhost:3010/oauth/check_token");
        return remoteTokenServices;
    }*/

    /**
     * HTTP安全配置
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 校验scope，对应认证服务的客户端详情配置的clientId
                .antMatchers("/**").access("#oauth2.hasScope('hrm')")
                // 关闭跨站伪造检查
                .and().csrf().disable()
                // 把session设置为无状态，意思是用了token，那么session不再做数据的记录
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
